angular.module('UCX.Cmis')
.directive 'autoSelectAll',(ModelService,$window,$rootScope,$timeout)->
  restrict:'A'
  link:(scope,ele,attr)->
    ####
####   auto select all text in an input element  ####
####       trigger click
    ####
    scope.select_succ=false
    scope.rangeSelect=(textField,start,end)->
    #    textField 可以是 document.getElementById('text') 也可以是 $('#text') 是一个对象
    #    start 表示的是 文字高亮的起始点 但是不包含该点
    #    end   表示  文字高亮区的结束点  包含
      if textField.createTextRange
    #   ie and opera
        selRange = textField.createTextRange()
        selRange.collapse(true)
        selRange.moveStart('character', start)
        selRange.moveEnd('character', end)
        selRange.select()
        textField.focus()
        scope.select_succ=true
      else if textField.setSelectionRange
    #      chrome firefox safari
        textField.focus()
        textField.setSelectionRange(start, end)
        scope.select_succ=true
      else if typeof textField.selectionStart != 'undefined'
    #      if not support
        textField.selectionStart = start
        textField.selectionEnd = end
        textField.focus()
        scope.select_succ=false
    #      只有当 input框的内容出现时候 才去执行 操作
    handleClick = ()->
      start = 0
      end = attr['value'].length
      textField = $(ele)[0]
      scope.rangeSelect(textField,start,end)
    ele[0].addEventListener('click',handleClick,false)
.directive 'qrcode',(ModelService,$window,$rootScope,$timeout)->
  restrict:'A'
  link:(scope,ele,attr)->
    ####
####  change url to qr ####
####
####
    ####
    init = ()->
      $timeout(()->
  #      if !attr['url']
  #        return false
  #      else
  #      console.log('qr',attr['url'])
        $(ele).empty()
        $(ele).qrcode({width: attr.width,height: attr.height,text:attr['url'] })
      ,200)
    init()
    scope.$watch(()->
      attr.url
    ,()->
      init()
    )

.directive('showTooltip',($window,$timeout,Utils)->
  restrict:'A'
  link:(scope,elem)->

    IE = Utils.browserIsIE
    timer=null
    init=()->
#      console.log $(elem).find('.tooltip-hint').width()
#      console.log $(elem).find('.tooltip-hint-parent').width()
#      需要处理 ie 的问题  ie 在计算有省略号的自动折叠 的内容 时候计算有问题
      if IE
        $(elem).find('.tooltip-hint-parent').find('.long-words-handle').css('width','auto')
      if $(elem).find('.tooltip-hint-parent').width()-12<=$(elem).find('.tooltip-hint').width()
#      show tooltip
#        console.log 'remove'
#        console.log $(elem).find('.tooltip-hint-parent').width()
#        console.log $(elem).find('.tooltip-hint').width()
        if $(elem).find('.tooltip-hint-parent').hasClass('not-show-tooltip')
          $(elem).find('.tooltip-hint-parent').removeClass('not-show-tooltip')
      else
#      hide tooltip
        $(elem).find('.tooltip-hint-parent').addClass('not-show-tooltip')
    #    发现一个有趣的 $timeout 这个方法 如果没有 提供 延迟参数 那么 他就会等待 html render 完毕执行 提供的方法
      if IE
        $(elem).find('.tooltip-hint-parent').find('.long-words-handle').css('width','100%')
    $timeout(init)
    #监控窗口宽度变化
    scope.$watch(
      ()->
        $window.innerWidth
      (newValue)->
        init()
    ,true)
).directive('btnClickEffect', ($timeout) ->
  {
    restrict: 'A'
    link: (scope, elem) ->
      $(elem).mousedown ->
        if $(this).hasClass('cbutton--click')
          $(this).removeClass 'cbutton--click'
        _this = $(this)
        setTimeout (->
          _this.addClass 'cbutton--click'
          return
        ), 0
        return
      #return elem[0].addEventListener('mousedown', function() {
      #  var _this
      #  if ($(this).hasClass('cbutton--click')) {
      #    $(this).removeClass('cbutton--click')
      #  }
      #  _this = $(this)
      #  return $timeout(function() {
      #    _this.addClass('cbutton--click')
      #  }, 0)
      #}, false)
      #  enter-key-event
      return

  }
).directive('enterKeyEvent', ($timeout) ->
  {
    restrict: 'A'
    link: (scope, elem) ->
      $(elem).keyup (e) ->
        if e.which == 13
          console.log scope
        return
      return

  }
).directive('clickEffect2', ->
# 从点击的中心点 散发出去一个效果
  {
    restrict: 'A'
    link: (scope, elem, attr) ->
      if $(elem).find('.ink-effect').length == 0
        elem.prepend '<span class="ink-effect"></span>'
      _this = $(elem)
      $(elem)[0].addEventListener 'touchstart', ((e) ->
        console.log 'touchstart'
        d = undefined
        ink = undefined
        x = undefined
        y = undefined
        ink = $(elem).find('.ink-effect')
        ink.removeClass 'animate'
        if !ink.height() and !ink.width()
          d = Math.max($(elem).outerWidth(), $(elem).outerHeight())
          ink.css
            height: d
            width: d
        x = e.touches[0].pageX - ($(elem).offset().left) - (ink.width() / 2)
        y = e.touches[0].pageY - ($(elem).offset().top) - (ink.height() / 2)
        ink.css(
          top: 0 + 'px'
          left: 0 + 'px').addClass 'animate'
      ), false
      $(elem)[0].addEventListener 'touchend', (->
        console.log 'touchend'
        return
      ), false
      $(elem)[0].addEventListener 'touchcancel', (->
        console.log 'touchend'
        return
      ), false
      #$(elem).mousedown(function(e) {
      #  var d, ink, x, y
      #  ink = $(this).find('.ink-effect')
      #  ink.removeClass('animate')
      #  if (!ink.height() && !ink.width()) {
      #    d = Math.max($(this).outerWidth(), $(this).outerHeight())
      #    ink.css({
      #      height: d,
      #      width: d
      #    })
      #  }
      #  x = e.pageX - $(this).offset().left - ink.width() / 2
      #  y = e.pageY - $(this).offset().top - ink.height() / 2
      #  return ink.css({
      #    top: 0 + 'px',
      #    left: 0 + 'px'
      #  }).addClass("animate")
      #})
      #var _this = $(elem)
      return

  }
).directive('clickEffectFromCircle', ->
# 从点击的中心点 散发出去一个效果
  {
    restrict: 'A'
    link: (scope, elem, attr) ->
      if $(elem).find('.ink-effect').length == 0
        elem.prepend '<span class="ink-effect"></span>'
      _this = $(elem)
      $(elem)[0].addEventListener 'touchstart', ((e) ->
#console.log('touchstart')
        d = undefined
        ink = undefined
        x = undefined
        y = undefined
        ink = $(elem).find('.ink-effect')
        ink.removeClass 'animate'
        ink.removeClass 'out'
        d = Math.max($(elem).outerWidth(), $(elem).outerHeight())
        ink.css
          height: d
          width: d
        #x = e.touches[0].pageX - $(elem).offset().left - ink.width() / 2
        #y = e.touches[0].pageY - $(elem).offset().top - ink.height() / 2
        x = e.touches[0].pageX
        y = e.touches[0].pageY
        ink.css(
          top: y + 'px'
          left: x + 'px').addClass 'animate'
      ), false
      ink[0].addEventListener 'animationstart', ((e) ->
      ), false
      ink[0].addEventListener 'animationend', ((e) ->
        ink.css
          height: '100%'
          width: '100%'
          borderRadius: 0
          left: 0
          top: 0
        return
      ), false
      $(elem)[0].addEventListener 'touchend', (->
#ink.addClass('out')
        return
      ), false
      return

  }
).directive('clickEffect', ->
# 从点击的中心点 散发出去一个效果
  {
    restrict: 'A'
    link: (scope, elem, attr) ->
      if $(elem).find('.ink-effect').length == 0
        elem.prepend '<span class="ink-effect"></span>'
      _this = $(elem)
      $(elem)[0].addEventListener 'touchstart', ((e) ->
        console.log 'touchstart'
        ink = undefined
        x = undefined
        y = undefined
        ink = $(elem).find('.ink-effect')
        ink.removeClass 'animate'
        ink.removeClass 'touchEnd'
        ink.removeClass 'animationEnd'
        ink.removeClass 'out'
        ink.css
          height: '100%'
          width: '100%'
        # x y 可以是 动态效果起始位置
        x = e.touches[0].pageX - ($(elem).offset().left) - (ink.width() / 2)
        y = e.touches[0].pageY - ($(elem).offset().top) - (ink.height() / 2)
        ink.css(
          top: 0 + 'px'
          left: 0 + 'px').addClass 'animate'
        return
      ), false
      $(elem).on 'animationstart', '.ink-effect', ->
        if $(this).hasClass('animationEnd')
          return false
        console.log 'animationstart'
        return
      $(elem).on 'animationend', '.ink-effect', ->
        if $(this).hasClass('animationEnd')
          return false
        console.log 'animationend'
        $(this).addClass 'animationEnd'
        # 需要计算 放大后的圆心 重叠需要的 移动
        d = Math.max($(elem).outerWidth(), $(elem).outerHeight())
        $(this).css
          height: '200%'
          width: '200%'
          top: '-' + d / 2 + 'px'
          left: '-' + d / 2 + 'px'
        if $(this).hasClass('touchEnd')
          $(this).addClass('out').removeClass 'animate'
        return
      $(elem)[0].addEventListener 'touchend', (->
        console.log 'touchend'
        $(this).find('.ink-effect').addClass 'touchEnd'
        if $(this).find('.ink-effect').hasClass('animationEnd')
          $(this).find('.ink-effect').addClass 'out'
        return
      ), false
      return

  }
).directive('imageLoadedEnd',(ModelService,$timeout,$rootScope)->
# image loaded
  {
    restrict: 'A'
    link: (scope, elem, attr) ->
      Judge = ()->
        if ModelService.allFiles[attr.id]
          if ModelService.allFiles[attr.id].thumbImgBig
            preloadUrl = ModelService.allFiles[attr.id].thumbImgBig
          else
            preloadUrl = ModelService.allFiles[attr.id].thumbImg
        # 这种方法 可以 判断出 图片是否加载过了 以及 是否加载
        # img.onload 这种方法  只能判断 一个 新链接放到img 标签是否加载完成 而无法判断已经存在的链接 是否加载过了
        img = new Image()
        img.src=preloadUrl
#        console.log img
#        console.log img.complete
#        console.log img.loadstart
#        console.log img.error
        if img.complete
          ModelService.allFiles[attr.id].thumbImgLoaded=true
        $(elem).one("load", ()->
          ModelService.allFiles[attr.id].thumbImgLoaded=true
          $timeout(()->
            scope.$apply()
            $rootScope.$apply()
          ,0)
        )

      scope.$watch(()->
        attr.id
      ,()->
        Judge()
      )
  }
)
.directive('dynamicWidth',($window,$timeout)->
#  this directive is to set element width dynamic as the window width is changed
  restrict:'A'
  link:(scope,elem)->
#    init     elem width:20%  min-width:190px
#    total parent width / min-width  result is a number  Math.floor(result)    elem width = 100%/result(int)
#    console.log elem
#    console.log elem[0].parentElement.clientWidth
#    margin的值是  16px
    timer1 = null
    margin=parseInt($(elem).css('marginRight'))
    onloadRightAside = $('#file-detail').width()
    init=()->
      totalWidth = elem[0].parentElement.clientWidth
      elemNumPerRow=Math.floor(totalWidth/(190+margin))
      totalMargin = elemNumPerRow*margin
      marginPercentage = Math.ceil(totalMargin*100/totalWidth)
      elemWidthPercentage=(100-marginPercentage)/elemNumPerRow+'%'
      elem[0].style.width=elemWidthPercentage
      if $(elem).find('.tooltip-hint-parent').width()<$(elem).find('.tooltip-hint').width()
        if $(elem).find('.tooltip-hint-parent').hasClass('not-show-tooltip')
          $(elem).find('.tooltip-hint-parent').removeClass('not-show-tooltip')
      else
        $(elem).find('.tooltip-hint-parent').addClass('not-show-tooltip')
    init()
    scope.$on('$destroy', ()->
      $timeout.cancel(timer1)
    )
    #监控窗口宽度变化
    w = angular.element($window)
    w.bind('resize',()->
      timer = $timeout ()->
        scope.$apply()
      , 0
      scope.$on('$destroy', ()->
        $timeout.cancel(timer)
      )
    )
    window.onload = ()->
      init()
    scope.$watch(
      ()->
        $window.innerWidth+' '+onloadRightAside
      (newValue)->
        init()
    ,true)
)
.directive 'lazyLoadImg', ($rootScope,$window,$timeout,ModelService)->
  restrict:'A'
  link:(scope,ele)->
#    只要获取到了 data-id 那么就开始进行初始化的操作
#    ele  代表的就是  img的父元素
#    getObjId 是一个异步  返回file 的 id
#    init 核心函数 判断 位置 并且绑定了一个 滚动时间
#    目录结构
#    console.log $('.fil-wrap').offset().top
#    console.log ele.offset().top
    getObjId=()->
      if ele[0].getAttribute('data-id').length>12
        objID = ele[0].getAttribute('data-id')
        init(objID)
      else
#       {{file.id}} 赋值会有点延迟 所以一直等到赋值结束 才执行
        $timeout(
          ()->
            getObjId()
        ,300)
    setImageSrc = (elem,src)->
      if !elem.attr('src')
        elem.attr('src',src)
      else
        return
    init=(objID)->
      obj=ModelService.getObjectById(objID)

      if $(ele).offset().top<$(document).height() && $(ele).offset().top>-20
        if obj.thumbImg
          setImageSrc($(ele).find('img'),obj.thumbImg)
        else
          obj.getRenditions(()->
            if obj.thumbImg
              setImageSrc($(ele).find('img'),obj.thumbImg)
            else if obj.thumbImgBig
              setImageSrc($(ele).find('img'),obj.thumbImgBig)
            else
              # default image
              setImageSrc($(ele).find('img'),'')
          )
    getObjId()
    $('.fil-wrap').bind('scroll',()->

      getObjId()
    )
.directive('progressBarModal',(UploadQueue)->
  templatePath='template-path/'
  restrict:'E'
  replace:true
  templateUrl:templatePath+'progress-bar.html'
  link:(scope)->
    scope.hasErrMsg=()->
      UploadQueue.hasErrMsg
    scope.isUploading = ()->
      UploadQueue.uploading
    scope.files=()->
      UploadQueue.queueFiles
    scope.isBarOpen=()->
      UploadQueue.barIsOpen
    scope.cancel=()->
#      $uibModalInstance.dismiss()
      UploadQueue.queueFiles = []
      $('#progress-bar-modal').hide('slow')
      #     coffee script the last statement will be the return sentence so add return true instead of return  $('#progress-bar-modal').hide('slow')
      return true
    scope.toggleQueue=()->
#      $('#progress-bar').toggle(300)
#      UploadQueue.hasErrMsg=false
      if UploadQueue.hasErrMsg
#        scope.hasErrMsg()
        UploadQueue.hasErrMsg=!UploadQueue.hasErrMsg

      #        UploadQueue.hasErrMsgFunc()
      UploadQueue.barIsOpen = !UploadQueue.barIsOpen
      UploadQueue.isBarOpen()
#      scope.$apply()
)
